package net.neiquan.applibrary.numberpicker.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;


import net.neiquan.applibrary.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


/**
 * 城市Picker
 *
 * @author zd
 *
 */
public class DatePicker extends LinearLayout {

	/** 滑动控件 */
	private ScrollerNumberPicker yearPicker;
	private ScrollerNumberPicker monthPicker; 
	private ScrollerNumberPicker dayPicker;
	/** 选择监听 */
	private OnSelectingListener onSelectingListener;
	/** 刷新界面 */
	private static final int REFRESH_VIEW = 0x001;
	/** 临时日期 */

	private int yearIndex = 0;
	private int monthIndex = 0;
	private int dayIndex = 0;
	private Context context;

	/**
	 * 所有年
	 */
	protected ArrayList<String> yearDatas;
	/**
	 * 所有月
	 */
	protected ArrayList<String> monthDatas;
	/**
	/**
	 * 所有日
	 */
	protected ArrayList<String> dayDatas;



	private Date startDate;
	private Date endDate;


	private String startDateStr="2015-01-01";
	private String endDateStr="2016-09-01";


	private int startYear;
	private int startMonth;
	private int startDay;
	private int endYear;
	private int endMonth;
	private int endDay;
	// 12个月  还还去除限制

	public DatePicker(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
		// TODO Auto-generated constructor stub
	}

	public DatePicker(Context context) {
		super(context);
		this.context = context;
		init();
	}


	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
				case REFRESH_VIEW:
					if (onSelectingListener != null)
						onSelectingListener.selected(true);
					break;
				default:
					break;
			}
		}

	};

	private void init(){
		LayoutInflater.from(getContext()).inflate(R.layout.city_picker, this);
		// 获取控件引用
		yearPicker = (ScrollerNumberPicker) findViewById(R.id.province);

		monthPicker = (ScrollerNumberPicker) findViewById(R.id.city);
		dayPicker = (ScrollerNumberPicker) findViewById(R.id.couny);
		initDate();
	}

	public void setDate(String startDateStr, String endDateStr){
		this.endDateStr=endDateStr;
		this.startDateStr=startDateStr;
		initDate();
	}
	public void setDate(Date startDate, Date endDate){
		this.startDate=startDate;
		this.endDate=endDate;
		initDate();
	}
	private void initDate(){

		yearDatas =new ArrayList<String>();
		monthDatas =new ArrayList<String>();
		dayDatas =new ArrayList<String>();


		if (startDate==null){
			startDate =stringToDate(startDateStr);
			endDate =stringToDate(endDateStr);
		}


		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		startYear = cal.get(Calendar.YEAR);
		startMonth = cal.get(Calendar.MONTH)+1;
		startDay =cal.get(Calendar.DAY_OF_MONTH);






		cal.setTime(endDate);

		endYear = cal.get(Calendar.YEAR);
		endMonth = cal.get(Calendar.MONTH)+1;
		endDay =cal.get(Calendar.DAY_OF_MONTH);

		// 计算年份
		for (int i=startYear;i<=endYear;i++){
			yearDatas.add(i+"");
		}

		// 12个月  还要去除限制  还要判断是不是最大月
		if (startYear==endYear){
			for (int i=startMonth;i<=endMonth;i++){
				monthDatas.add(i+"");
			}
		}else{
			for (int i=startMonth;i<=12;i++){
				monthDatas.add(i+"");
			}
		}


		// 获取某年某月有多少天
        // 还要去除限制
		if (startYear==endYear && startMonth==endMonth){
			for (int i=startDay;i<=endDay;i++){
				dayDatas.add(i+"");
			}
		}else{
			int maxday =days(startYear,startMonth);
			for (int i=startDay;i<=maxday;i++){
				dayDatas.add(i+"");
			}
		}


		yearPicker.setData(yearDatas);
		yearPicker.setDefault(0);

		monthPicker.setData(monthDatas);
		monthPicker.setDefault(0);

		dayPicker.setData(dayDatas);
		dayPicker.setDefault(0);

		yearPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

			@Override
			public void endSelect(int id, String text) {
				// TODO Auto-generated method stub
				yearIndex =id;

				// 12个月  还还去除限制
				// 先判断是不是到最小的年  或者到大的年
				monthDatas =new ArrayList<String>();
				if(yearDatas.get(yearIndex).equals(startYear+"")){
					if (yearDatas.get(yearIndex).equals(endYear+"")){
						for (int i=startMonth;i<=endMonth;i++){
							monthDatas.add(i+"");
						}
					}else {
						for (int i=startMonth;i<=12;i++){
							monthDatas.add(i+"");
						}
					}

				}else  if (yearDatas.get(yearIndex).equals(endYear+"")){
					for (int i=1;i<=endMonth;i++){
						monthDatas.add(i+"");
					}
				}else{
					for (int i=1;i<=12;i++){
						monthDatas.add(i+"");
					}
				}
				// 判断日期是否超过 超过自动减少
				while (monthIndex>=monthDatas.size()) {
					monthIndex--;
				}

				monthPicker.setData(monthDatas);
				monthPicker.setDefault(monthIndex);

                // 判断日是否过期
				dayDatas =new ArrayList<String>();

				// 选到开始年 开始月 要算天了
				if(yearDatas.get(yearIndex).equals(startYear+"") && monthDatas.get(monthIndex).equals(startMonth+"")){
					// 判断是不是开始月和结束月一样
					if(yearDatas.get(yearIndex).equals(endYear+"") && monthDatas.get(monthIndex).equals(endMonth+"")){
						for (int i=startDay;i<=endDay;i++){
							dayDatas.add(i+"");
						}
					}
					else {
						int maxday =days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
						for (int i=startDay;i<=maxday;i++){
							dayDatas.add(i+"");
						}
					}

				}else if(yearDatas.get(yearIndex).equals(endYear+"") && monthDatas.get(monthIndex).equals(endMonth+"")){
					// 结束年不会和开始年月 在同一天
					int maxday =days(endYear,endMonth);
					for (int i=1;i<=endDay;i++){
						dayDatas.add(i+"");
					}
				}else{
					int maxday =days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
					for (int i=1;i<=maxday;i++){
						dayDatas.add(i+"");
					}
				}
				// 判断日期是否超过 超过自动减少
				while (dayIndex>=dayDatas.size()) {
					dayIndex--;
				}
				dayPicker.setData(dayDatas);
				dayPicker.setDefault(dayIndex);
				Message message = new Message();
				message.what = REFRESH_VIEW;
				handler.sendMessage(message);
			}

			@Override
			public void selecting(int id, String text) {
				// TODO Auto-generated method stub
			}
		});
		monthPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

			@Override
			public void endSelect(int id, String text) {
				// TODO Auto-generated method stub
				monthIndex =id;
				dayDatas =new ArrayList<String>();

				// 选到开始年 开始月 要算天了
				if(yearDatas.get(yearIndex).equals(startYear+"") && monthDatas.get(monthIndex).equals(startMonth+"")){
					// 判断是不是开始月和结束月一样
					if(yearDatas.get(yearIndex).equals(endYear+"") && monthDatas.get(monthIndex).equals(endMonth+"")){
						for (int i=startDay;i<=endDay;i++){
							dayDatas.add(i+"");
						}
					}
					else {
						int maxday =days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
						for (int i=startDay;i<=maxday;i++){
							dayDatas.add(i+"");
						}
					}

				}else if(yearDatas.get(yearIndex).equals(endYear+"") && monthDatas.get(monthIndex).equals(endMonth+"")){
					// 结束年不会和开始年月 在同一天
					int maxday =days(endYear,endMonth);
					for (int i=1;i<=endDay;i++){
						dayDatas.add(i+"");
					}
				}else{
					int maxday =days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
					for (int i=1;i<=maxday;i++){
						dayDatas.add(i+"");
					}
				}
				// 判断日期是否超过 超过自动减少
				while (dayIndex>=dayDatas.size()) {
					dayIndex--;
				}
				dayPicker.setData(dayDatas);
				dayPicker.setDefault(dayIndex);
			}

			@Override
			public void selecting(int id, String text) {

			}
		});
		dayPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

			@Override
			public void endSelect(int id, String text) {
				dayIndex = id;
				Message message = new Message();
				message.what = REFRESH_VIEW;
				handler.sendMessage(message);
			}

			@Override
			public void selecting(int id, String text) {

			}
		});
	}
	public  int days(int year, int month) {
		int days = 0;
		if (month != 2) {
			switch (month) {
				case 1:
				case 3:
				case 5:
				case 7:
				case 8:
				case 10:
				case 12:
					days = 31;
					break;
				case 4:
				case 6:
				case 9:
				case 11:
					days = 30;

			}
		} else {
			//闰年
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
				days = 29;
			else
				days = 28;

		}
		return days;

	}
	/**
	 * string类型转换为date类型
	 * @param strTime
	 * @return
	 */
	public Date stringToDate(String strTime){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = formatter.parse(strTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block;
			Log.e("date error", e.toString());
		}
		return date;
	}
	public Date getSelectDate(){
		return  stringToDate(yearDatas.get(yearIndex)+"-"+monthDatas.get(monthIndex)+"-"+dayDatas.get(dayIndex));
	}

	public String getSelectDateStr(){
		return  new SimpleDateFormat("yyyy-MM-dd").format(getSelectDate());
	}
	public void setOnSelectingListener(OnSelectingListener onSelectingListener) {
		this.onSelectingListener = onSelectingListener;
	}
	public interface OnSelectingListener {
		public void selected(boolean selected);
	}

}